<template>
  <div class="aaa">
    <el-cascader ref="addressSelect" size="small" :props="opt" :options="options" v-model="values"
                 @change="addressChange"
                 placeholder="请选择区域">
    </el-cascader>
  </div>
</template>

<script>
import * as locationApi from '@/api/sys/location'

export default {
  name: "addressSelect",
  props: {
    root: {
      type: String,
      default() {
        return 'ROOT'
      }
    },
    checkStrictly: {
      type: Boolean,
      default() {
        return false
      }
    },
    endLv: {
      type: Number,
      default() {
        return 3
      }
    }
  },
  data() {
    let t = this;
    return {
      values: [],
      options: [],
      test: '测试数据',
      opt: {
        checkStrictly: t.checkStrictly,
        lazy: true,
        lazyLoad(node, resolve) {
          t.initData(node, resolve);
        }
      },
    }
  },
  methods: {
    setDefaultHandler(defaultSelect) {
      locationApi.querySelect(defaultSelect).then(res => {
        console.log(defaultSelect)
        this.options = []
        this.options = res.data
        this.values = defaultSelect
      })
    },
    clearValueHandler() {
      this.values = []
    },
    getSelectLabel() {
      let value = this.$refs.addressSelect.getCheckedNodes()
      if (value.length === 0) {
        return []
      } else {
        return value[0].pathLabels
      }
    },
    getSelectValue() {
      let value = this.$refs.addressSelect.getCheckedNodes()
      if (value.length === 0) {
        return []
      } else {
        return value[0].path
      }
    },
    addressChange(values) {
      this.$emit('addressChange', values)
    },
    initData(node, resolve) {
      //  如果已经加载过就不再加载了
      if (node.children && node.children.length > 0) {
        resolve()
      } else {
        let parentCode = '';
        if (node.root) {
          parentCode = this.root
        } else {
          parentCode = node.data.value
        }
        //  到达顶级了直接返回
        if (node.level >= this.endLv) {
          resolve()
        }
        locationApi.query(parentCode).then(res => {
          if (res.data && res.data.length > 0) {
            const nodes = []
            res.data.forEach(o => {
              nodes.push({
                value: o.code,
                label: o.name,
                leaf: o.lvl >= this.endLv
              })
            })
            resolve(nodes)
          } else {
            resolve()
          }
        })
      }
    }
  }
}
</script>

<style>
</style>
